package sein.android.hopenote;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.daum.adam.publisher.AdView;
import net.daum.adam.publisher.AdView.AnimationType;
import net.daum.adam.publisher.AdView.OnAdClickedListener;
import net.daum.adam.publisher.AdView.OnAdClosedListener;
import net.daum.adam.publisher.AdView.OnAdFailedListener;
import net.daum.adam.publisher.AdView.OnAdLoadedListener;
import net.daum.adam.publisher.AdView.OnAdWillLoadListener;
import net.daum.adam.publisher.impl.AdError;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.tools.PanListener;
import org.achartengine.tools.ZoomEvent;
import org.achartengine.tools.ZoomListener;

import com.mocoplex.adlib.AdlibActivity;
import com.mocoplex.adlib.AdlibConfig;

import sein.android.hopenote.Const.HopeNoteDb;

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Note_Chart extends AdlibActivity {
	public static final String TYPE = "type";

	private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();

	private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();

	private XYSeries mSeries1, mSeries2, mSeriesFR, mSeriesTO;

	private XYSeriesRenderer mRenderer1, mRenderer2, mRendererFR, mRendererTO;

	private String mDateFormat;

	private Button show;

	private TextView item;

	private EditText et_year, et_month;

	private GraphicalView mChartView;

	private int index = 0;

	private DBAdapter HnopenHelper;
	private SQLiteDatabase sdb;
	private String str_Item, str_User, str_Unit, str_Cnt;
	private Cursor normal, list_cur;
	private double normal_fr, normal_to;
	
	/*
	//Var for Ad@m
	private AdView adView = null;
	private static final String LOGTAG = "BannerTypeXML1";
	*/

	@Override
	protected void onRestoreInstanceState(Bundle savedState) {
		super.onRestoreInstanceState(savedState);
		mDataset = (XYMultipleSeriesDataset) savedState
				.getSerializable("dataset");
		mRenderer = (XYMultipleSeriesRenderer) savedState
				.getSerializable("renderer");
		mSeries1 = (XYSeries) savedState.getSerializable("series1");
		mSeries2 = (XYSeries) savedState.getSerializable("series2");
		mSeriesFR = (XYSeries) savedState.getSerializable("seriesFR");
		mSeriesTO = (XYSeries) savedState.getSerializable("seriesTO");
		mRenderer1 = (XYSeriesRenderer) savedState.getSerializable("renderer1");
		mRenderer2 = (XYSeriesRenderer) savedState.getSerializable("renderer2");
		mRendererFR = (XYSeriesRenderer) savedState
				.getSerializable("rendererFR");
		mRendererTO = (XYSeriesRenderer) savedState
				.getSerializable("rendererTO");
		mDateFormat = savedState.getString("date_format");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("dataset", mDataset);
		outState.putSerializable("renderer", mRenderer);
		outState.putSerializable("series1", mSeries1);
		outState.putSerializable("series2", mSeries2);
		outState.putSerializable("seriesFR", mSeriesFR);
		outState.putSerializable("seriesTO", mSeriesTO);
		outState.putSerializable("renderer1", mRenderer1);
		outState.putSerializable("renderer2", mRenderer2);
		outState.putSerializable("rendererFR", mRendererFR);
		outState.putSerializable("rendererTO", mRendererTO);
		outState.putString("date_format", mDateFormat);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_chart);

		HnopenHelper = new DBAdapter(this);
		sdb = HnopenHelper.getReadableDatabase();
		
		// Ad@m Ad
		//initAdam();
		
		// 광고 호출
		this.setAdsContainer(R.id.ads);

		str_User = HopeNoteDb.CURRENT_USER; // 사용자 명
		str_Item = HopeNoteDb.CURRENT_ITEM; // 항목 명
		str_Unit = HopeNoteDb.CURRENT_UNIT; // 단위
		str_Cnt = HopeNoteDb.CURRENT_CNT; // 입력 수

		normal_fr = 0.0;
		normal_to = 0.0;

		item = (TextView) findViewById(R.id.item);
		et_year = (EditText) findViewById(R.id.year);
		et_month = (EditText) findViewById(R.id.month);

		SimpleDateFormat dt_year = new SimpleDateFormat("yyyy");
		SimpleDateFormat dt_month = new SimpleDateFormat("MM");
		Date date = new Date();
		// test
		et_year.setText(dt_year.format(date));
		et_month.setText(dt_month.format(date));

		mRenderer.setApplyBackgroundColor(true);
		mRenderer.setBackgroundColor(Color.argb(255, 255, 255, 190));
		mRenderer.setAxisTitleTextSize(16);
		mRenderer.setChartTitleTextSize(20);
		mRenderer.setLabelsTextSize(10);
		mRenderer.setLabelsColor(Color.DKGRAY);
		mRenderer.setLegendTextSize(15);
		mRenderer.setMargins(new int[] { 20, 30, 30, 10 });
		mRenderer.setZoomButtonsVisible(false);
		mRenderer.setPointSize(4);
		mRenderer.setXTitle("일별");
		mRenderer.setYTitle("수치");
		mRenderer.setShowGrid(true);
		mRenderer.setGridColor(Color.rgb(150, 150, 150));
		mRenderer.setMarginsColor(Color.rgb(255, 238, 238));
		mRenderer.setXAxisMin(0.5);
		mRenderer.setXAxisMax(31.5);
		mRenderer.setYAxisMin(-0.5);
		mRenderer.setYAxisMax(300);
		mRenderer.setXLabels(31);
		mRenderer.setYLabels(6);
		mRenderer.setPanEnabled(false, true);
		mRenderer.setZoomEnabled(false, true);
		
		// set new Series
		// From
		String seriesTitle = "상한";
		XYSeries series = new XYSeries(seriesTitle);
		mDataset.addSeries(series);
		mSeriesTO = series;
		XYSeriesRenderer renderer = new XYSeriesRenderer();
		mRenderer.addSeriesRenderer(renderer);
		// renderer.setPointStyle(PointStyle.CIRCLE);
		renderer.setFillPoints(false);
		renderer.setColor(Color.argb(255, 190, 255, 190));
		renderer.setFillBelowLine(true);
		renderer.setFillBelowLineColor(Color.argb(255, 190, 255, 190));
		mRendererTO = renderer;

		// To
		seriesTitle = "하한";
		series = new XYSeries(seriesTitle);
		mDataset.addSeries(series);
		mSeriesFR = series;
		renderer = new XYSeriesRenderer();
		mRenderer.addSeriesRenderer(renderer);
		// renderer.setPointStyle(PointStyle.CIRCLE);
		renderer.setFillPoints(false);
		renderer.setColor(Color.argb(255, 190, 255, 190));
		renderer.setFillBelowLine(true);
		renderer.setFillBelowLineColor(Color.argb(255, 255, 255, 190));
		mRendererFR = renderer;
		
		// 입력 1
		seriesTitle = "입력1";
		series = new XYSeries(seriesTitle);
		mDataset.addSeries(series);
		mSeries1 = series;
		renderer = new XYSeriesRenderer();
		mRenderer.addSeriesRenderer(renderer);
		renderer.setPointStyle(PointStyle.CIRCLE);
		renderer.setFillPoints(true);
		renderer.setColor(Color.BLACK);
		renderer.setLineWidth(2);
		renderer.setDisplayChartValues(true);
		mRenderer1 = renderer;

		// 입력 2
		seriesTitle = "입력2";
		series = new XYSeries(seriesTitle);
		mDataset.addSeries(series);
		mSeries2 = series;
		renderer = new XYSeriesRenderer();
		mRenderer.addSeriesRenderer(renderer);
		renderer.setPointStyle(PointStyle.CIRCLE);
		renderer.setFillPoints(true);
		renderer.setColor(Color.BLACK);
		renderer.setLineWidth(2);
		renderer.setDisplayChartValues(true);
		mRenderer2 = renderer;
		// end

		if (mChartView != null) {
			mChartView.repaint();
		}

		show = (Button) findViewById(R.id.show);
		
		// 년/월 자동완성
        
		et_year.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				/*
				if(Integer.valueOf(s.toString()) < 1900)
				{
					et_year.setText("1900");
				}
				else if (Integer.valueOf(s.toString()) > 9999)
				{
					et_year.setText("9999");
				}
				*/
				if(s.length() > 4)
				{
					et_year.setText("");
				}
			}
		});
        
        et_month.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
			}
			
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				/*
				if(s.toString().length() == 1)
				{
					et_month.setText("0"+s.toString());
				}
				else
					if (Integer.valueOf(s.toString()) > 12)
				{
					et_month.setText("12");
				}
				*/
				if(s.length() > 2)
				{
					et_month.setText("");
				}
			}
		});
		

		show.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				et_year.clearFocus();
				et_month.clearFocus();
				
				//자동완성
				if(Integer.valueOf(et_year.getText().toString()) < 1900)
				{
					et_year.setText("1900");
				}
				else if (Integer.valueOf(et_year.getText().toString()) > 9999)
				{
					et_year.setText("9999");
				}
				
				if(et_month.getText().toString().length() == 1)
				{
					et_month.setText("0"+et_month.getText().toString());
				}
				else if (Integer.valueOf(et_month.getText().toString()) > 12)
				{
					et_month.setText("12");
				}
				else if (Integer.valueOf(et_month.getText().toString()) < 1)
				{
					et_month.setText("01");
				}
				
				if (HopeNoteDb.CURRENT_USER.equals("")) {
					Toast.makeText(Note_Chart.this, "메뉴키를 눌러 사용자를 선택해주세요.",
							Toast.LENGTH_SHORT).show();
				} else if (HopeNoteDb.CURRENT_ITEM.equals("")) {
					Toast.makeText(Note_Chart.this, "메뉴키를 눌러 항목 선택해주세요.",
							Toast.LENGTH_SHORT).show();
				} else {
					try {
						double x = Double
								.parseDouble(et_year.getText().toString());
						if (1900 > x || x > 9999) {
							et_year.requestFocus();
							return;
						}
					} catch (NumberFormatException e) {
						// TODO
						et_year.requestFocus();
						return;
					}

					try {
						double y = Double.parseDouble(et_month.getText()
								.toString());
						if (1 > y || y > 12) {
							et_month.requestFocus();
							return;
						} else {
							if (et_month.getText().length() == 1) {
								et_month.setText("0" + et_month.getText().toString());
							}
						}
					} catch (NumberFormatException e) {
						// TODO
						et_month.requestFocus();
						return;
					}

					// clear
					str_User = HopeNoteDb.CURRENT_USER; // 사용자 명
					str_Item = HopeNoteDb.CURRENT_ITEM; // 항목 명
					str_Unit = HopeNoteDb.CURRENT_UNIT; // 단위
					str_Cnt = HopeNoteDb.CURRENT_CNT; // 입력 수

					item.setText(str_Item);

					normal_fr = 0.0;
					normal_to = 0.0;

					mSeries1.clear();
					mSeries2.clear();
					mSeriesFR.clear();
					mSeriesTO.clear();

					if (str_Cnt.equals("2")) {
						mSeries1.setTitle(str_Item + "1");
						mSeries2.setTitle(str_Item + "2");
						mRenderer2.setColor(Color.BLACK);
					} else {
						mSeries1.setTitle(str_Item);
						mSeries2.setTitle("");
						mRenderer2.setColor(Color.argb(0, 0, 0, 0));
					}
					
					// DATA
					String getColumns[] = { HopeNoteDb.COL_NORMAL_FR,
							HopeNoteDb.COL_NORMAL_TO };
					String qWhere = HopeNoteDb.COL_USER + " = '" + str_User
							+ "' AND " + HopeNoteDb.COL_ITEM + " = '"
							+ str_Item + "'";
					
					normal = sdb.query(HopeNoteDb.TB_NORMAL, getColumns,
							qWhere, null, null, null, null);

					if (normal.getCount() > 0) {
						normal.moveToFirst();
						normal_fr = normal.getDouble(0);
						normal_to = normal.getDouble(1);
						
						Log.i("log", String.valueOf(normal_fr));
						Log.i("log", String.valueOf(normal_to));
						

						mSeriesTO.add(0.5, normal_to);
						mSeriesTO.add(31.5, normal_to);
						mSeriesFR.add(0.5, normal_fr);
						mSeriesFR.add(31.5, normal_fr);
					}
					/*
					 * getColumns = new String[] { "strftime('%d'," +
					 * HopeNoteDb.COL_DATE + ") as "+ HopeNoteDb.COL_DATE,"AVG("
					 * + HopeNoteDb.COL_DOCUMENT1 + ") as "+
					 * HopeNoteDb.COL_DOCUMENT1, "AVG(" +
					 * HopeNoteDb.COL_DOCUMENT2 + ") as " +
					 * HopeNoteDb.COL_DOCUMENT2 }; qWhere = qWhere +
					 * " AND strftime('%Y%m'," + HopeNoteDb.COL_DATE + ") = '" +
					 * year.getText().toString() + month.getText().toString() +
					 * "'";
					 * 
					 * list_cur = sdb.query(HopeNoteDb.TB_NOTE, getColumns,
					 * qWhere, null, "strftime('%d'," + HopeNoteDb.COL_DATE +
					 * ")", null, null);
					 */

					list_cur = sdb.rawQuery("SELECT strftime('%d',"
							+ HopeNoteDb.COL_DATE + ") as day" + ", AVG("
							+ HopeNoteDb.COL_DOCUMENT1 + ") as document1"
							+ ", AVG(" + HopeNoteDb.COL_DOCUMENT2
							+ ") as document2" + " FROM " + HopeNoteDb.TB_NOTE
							+ " WHERE " + HopeNoteDb.COL_USER + " = '"
							+ str_User + "'" + " AND " + HopeNoteDb.COL_ITEM
							+ " = '" + str_Item + "'" + " AND strftime('%Y%m',"
							+ HopeNoteDb.COL_DATE + ") = '"
							+ et_year.getText().toString()
							+ et_month.getText().toString() + "'"
							+ " GROUP BY day" + " ORDER BY day;", null);
					// DATA END

					//최대값 / 최소값
					double maxValue = 0;
					double minValue = 9999999;
					
					// Set Chart Data
					list_cur.moveToFirst();
					while (!list_cur.isAfterLast())
					{
						mSeries1.add(list_cur.getDouble(0), list_cur.getDouble(1));
						
						//최대값,최소값 설정 
						if(maxValue < list_cur.getDouble(1))
						{
							maxValue = list_cur.getDouble(1);
						}
						if(minValue > list_cur.getDouble(1))
						{
							minValue = list_cur.getDouble(1);
						}
						
						if (str_Cnt.equals("2"))
						{
							mSeries2.add(list_cur.getDouble(0), list_cur.getDouble(2));
							
							//최대값, 최소값 설정
							if(maxValue < list_cur.getDouble(2))
							{
								maxValue = list_cur.getDouble(2);
							}
							if(minValue > list_cur.getDouble(2))
							{
								minValue = list_cur.getDouble(2);
							}
						}

						list_cur.moveToNext();
					}
					
					//그래프 Y축 범위 설
					maxValue = maxValue * 1.1;
					minValue = minValue * 0.9;
					mRenderer.setYAxisMax(maxValue);
					mRenderer.setYAxisMin(minValue);

					et_month.requestFocus();

					if (mChartView != null) {
						mChartView.repaint();
					}
					Bitmap bitmap = mChartView.toBitmap();
					try {
						File file = new File(Environment
								.getExternalStorageDirectory(), "test"
								+ index++ + ".png");
						FileOutputStream output = new FileOutputStream(file);
						bitmap.compress(CompressFormat.PNG, 100, output);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}


	@Override
	protected void onResume() {
		super.onResume();
		if (mChartView == null) {
			LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
			mChartView = ChartFactory.getLineChartView(this, mDataset,
					mRenderer);
			mRenderer.setClickEnabled(true);
			mRenderer.setSelectableBuffer(100);
			mChartView.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					SeriesSelection seriesSelection = mChartView
							.getCurrentSeriesAndPoint();
					if (seriesSelection == null) {
					} else {
						Toast.makeText(
								Note_Chart.this,
								seriesSelection.getXValue()
										+ "일  "
										+ "입력"
										+ (seriesSelection.getSeriesIndex() - 1)
										+ " 평균 : " + seriesSelection.getValue(),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
			mChartView.setOnLongClickListener(new View.OnLongClickListener() {
				public boolean onLongClick(View v) {
					SeriesSelection seriesSelection = mChartView
							.getCurrentSeriesAndPoint();
					if (seriesSelection == null) {
						Toast.makeText(Note_Chart.this,
								"No chart element was long pressed",
								Toast.LENGTH_SHORT);
						return false; // no chart element was long pressed, so
										// let something
						// else handle the event
					} else {
						Toast.makeText(Note_Chart.this,
								"Chart element in series index "
										+ seriesSelection.getSeriesIndex()
										+ " data point index "
										+ seriesSelection.getPointIndex()
										+ " was long pressed",
								Toast.LENGTH_SHORT);
						return true; // the element was long pressed - the event
										// has been
						// handled
					}
				}
			});
			mChartView.addZoomListener(new ZoomListener() {
				public void zoomApplied(ZoomEvent e) {
					String type = "out";
					if (e.isZoomIn()) {
						type = "in";
					}
					System.out.println("Zoom " + type + " rate "
							+ e.getZoomRate());
				}

				public void zoomReset() {
					System.out.println("Reset");
				}
			}, true, true);
			mChartView.addPanListener(new PanListener() {
				public void panApplied() {
					System.out.println("New X range=["
							+ mRenderer.getXAxisMin() + ", "
							+ mRenderer.getXAxisMax() + "], Y range=["
							+ mRenderer.getYAxisMax() + ", "
							+ mRenderer.getYAxisMax() + "]");
				}
			});
			layout.addView(mChartView, new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			boolean enabled = mDataset.getSeriesCount() > 0;
		} else {
			mChartView.repaint();
		}
	}

	/*
	//Ad@m
	private void initAdam() {
		// Ad@m sdk 초기화 시작
		adView = (AdView) findViewById(R.id.adview);
		// 광고 리스너 설정
		// 1. 광고 클릭시 실행할 리스너
		adView.setOnAdClickedListener(new OnAdClickedListener() {
			public void OnAdClicked() {
				Log.i(LOGTAG, "광고를 클릭했습니다.");
			}
		});
		// 2. 광고 내려받기 실패했을 경우에 실행할 리스너
		adView.setOnAdFailedListener(new OnAdFailedListener() {
			public void OnAdFailed(AdError error, String message) {
				Log.w(LOGTAG, message);
			}
		});
		// 3. 광고를 정상적으로 내려받았을 경우에 실행할 리스너
		adView.setOnAdLoadedListener(new OnAdLoadedListener() {
			public void OnAdLoaded() {
				Log.i(LOGTAG, "광고가 정상적으로 로딩되었습니다.");
			}
		});// 4. 광고를 불러올때 실행할 리스너
		adView.setOnAdWillLoadListener(new OnAdWillLoadListener() {
			public void OnAdWillLoad(String url) {
				Log.i(LOGTAG, "광고를 불러옵니다. : " + url);
			}
		});
		// 5. 젂면형 광고를 닫았을때 실행할 리스너
		adView.setOnAdClosedListener(new OnAdClosedListener() {
			public void OnAdClosed() {
				Log.i(LOGTAG, "광고를 닫았습니다.");
			}
		});
		// 할당 받은 clientId 설정
		// adView.setClientId(“TestClientId”);
		// 광고 갱싞 주기를 12초로 설정
		// adView.setRequestInterval(12);
		// 광고 영역에 캐시 사용 여부 : 기본 값은 true
		adView.setAdCache(false);
		// Animation 효과 : 기본 값은 AnimationType.NONE
		adView.setAnimationType(AnimationType.FLIP_HORIZONTAL);
		adView.setVisibility(View.VISIBLE);
	}
	*/
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		/*
		//Ad@m 종료
		if (adView != null) {
			adView.destroy();
			adView = null;
		}
		*/
	}
}
